<template>
  <div class="chat-interface">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="header-left">
        <el-avatar :size="40" src="/icons/ai-avatar.png">AI</el-avatar>
        <div class="header-info">
          <h3>智能客服助手</h3>
          <span class="status online">在线</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="text" @click="showHistory = true">
          <el-icon><Clock /></el-icon>
          历史记录
        </el-button>
        <el-button type="text" @click="handleCloseConversation">
          <el-icon><Close /></el-icon>
          结束对话
        </el-button>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message', message.type]"
      >
        <div class="message-avatar">
          <el-avatar :size="32" v-if="message.type === 'ai'">AI</el-avatar>
          <el-avatar :size="32" v-else>{{ userName.charAt(0) }}</el-avatar>
        </div>
        <div class="message-content">
          <div class="message-bubble">
            <div class="message-text" v-html="message.content"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
      
      <!-- AI正在输入提示 -->
      <div v-if="isAiTyping" class="message ai">
        <div class="message-avatar">
          <el-avatar :size="32">AI</el-avatar>
        </div>
        <div class="message-content">
          <div class="message-bubble">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-container">
        <el-input
          v-model="currentMessage"
          type="textarea"
          :rows="2"
          placeholder="请输入您的问题..."
          @keydown.enter="handleSendMessage"
          :disabled="isAiTyping"
          resize="none"
        />
        <div class="input-actions">
          <el-button type="text" @click="showQuickReplies = !showQuickReplies">
            <el-icon><ChatDotRound /></el-icon>
            快捷回复
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSendMessage"
            :loading="isAiTyping"
            :disabled="!currentMessage.trim()"
          >
            发送
          </el-button>
        </div>
      </div>
      
      <!-- 快捷回复 -->
      <div v-if="showQuickReplies" class="quick-replies">
        <el-tag 
          v-for="reply in quickReplies" 
          :key="reply"
          @click="selectQuickReply(reply)"
          class="quick-reply-tag"
        >
          {{ reply }}
        </el-tag>
      </div>
    </div>

    <!-- 满意度评价对话框 -->
    <el-dialog v-model="showRating" title="服务评价" width="400px">
      <div class="rating-content">
        <p>请为本次服务打分：</p>
        <el-rate v-model="satisfaction.rating" :max="5" show-text />
        <el-input
          v-model="satisfaction.feedback"
          type="textarea"
          :rows="3"
          placeholder="请输入您的反馈意见（可选）"
          style="margin-top: 15px;"
        />
        <div style="margin-top: 15px;">
          <el-checkbox v-model="satisfaction.isResolved">问题已解决</el-checkbox>
        </div>
      </div>
      <template #footer>
        <el-button @click="showRating = false">取消</el-button>
        <el-button type="primary" @click="submitRating">提交评价</el-button>
      </template>
    </el-dialog>

    <!-- 历史记录对话框 -->
    <el-dialog v-model="showHistory" title="对话历史" width="60%">
      <ConversationHistory @select-conversation="loadConversation" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock, Close, ChatDotRound } from '@element-plus/icons-vue'
import { AICustomerService } from '@/services/aiCustomerService'
// @ts-ignore
import ConversationHistory from './ConversationHistory.vue'

// 消息接口
interface Message {
  type: 'user' | 'ai'
  content: string
  timestamp: Date
}

// 响应式数据
const messages = ref<Message[]>([])
const currentMessage = ref('')
const isAiTyping = ref(false)
const showQuickReplies = ref(false)
const showRating = ref(false)
const showHistory = ref(false)
const messagesContainer = ref<HTMLElement>()
const userName = ref('用户')
const sessionId = ref('')

// 满意度评价
const satisfaction = ref({
  rating: 5,
  feedback: '',
  isResolved: false
})

// 快捷回复
const quickReplies = ref([
  '你好',
  '谢谢',
  '我需要帮助',
  '产品咨询',
  '技术支持',
  '订单查询',
  '退换货',
  '联系人工客服'
])

// 初始化
onMounted(() => {
  // 生成会话ID
  sessionId.value = 'session_' + Date.now()
  
  // 添加欢迎消息
  messages.value.push({
    type: 'ai',
    content: '您好！我是智能客服助手，很高兴为您服务。请问有什么可以帮助您的吗？',
    timestamp: new Date()
  })
})

// 发送消息
const handleSendMessage = async (event?: KeyboardEvent) => {
  if (event && event.shiftKey) {
    return // Shift+Enter 换行
  }
  
  if (event) {
    event.preventDefault()
  }
  
  if (!currentMessage.value.trim() || isAiTyping.value) {
    return
  }
  
  const userMessage = currentMessage.value.trim()
  currentMessage.value = ''
  
  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: userMessage,
    timestamp: new Date()
  })
  
  // 滚动到底部
  scrollToBottom()
  
  // 显示AI正在输入
  isAiTyping.value = true
  
  try {
    // 调用AI接口
    const response = await AICustomerService.chat({
      sessionId: sessionId.value,
      userMessage,
      userName: userName.value,
      messageType: 'text'
    })
    
    // 添加AI回复
    messages.value.push({
      type: 'ai',
      content: response.message || '抱歉，我暂时无法理解您的问题，请稍后重试或联系人工客服。',
      timestamp: new Date()
    })
    
  } catch (error) {
    // 错误处理
    messages.value.push({
      type: 'ai',
      content: '抱歉，服务暂时不可用，请稍后重试。',
      timestamp: new Date()
    })
    ElMessage.error('发送消息失败')
  } finally {
    isAiTyping.value = false
    scrollToBottom()
  }
}

// 选择快捷回复
const selectQuickReply = (reply: string) => {
  currentMessage.value = reply
  showQuickReplies.value = false
  handleSendMessage()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 结束对话
const handleCloseConversation = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要结束当前对话吗？结束后将进行服务评价。',
      '结束对话',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    showRating.value = true
  } catch {
    // 用户取消
  }
}

// 提交评价
const submitRating = async () => {
  try {
    await AICustomerService.rateSatisfaction({
      conversationId: 0, // 这里需要实际的对话ID
      satisfactionRating: satisfaction.value.rating,
      feedback: satisfaction.value.feedback,
      isResolved: satisfaction.value.isResolved
    })
    
    await AICustomerService.closeConversation('用户主动结束')
    
    ElMessage.success('感谢您的评价！')
    showRating.value = false
    
    // 重置对话
    messages.value = []
    sessionId.value = 'session_' + Date.now()
    
    // 添加新的欢迎消息
    messages.value.push({
      type: 'ai',
      content: '感谢您的评价！如果您还有其他问题，请随时告诉我。',
      timestamp: new Date()
    })
    
  } catch (error) {
    ElMessage.error('提交评价失败')
  }
}

// 加载历史对话
const loadConversation = (conversation: any) => {
  // 这里可以加载选中的历史对话
  showHistory.value = false
  ElMessage.info('历史对话加载功能待实现')
}
</script>

<style scoped>
.chat-interface {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-info h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.status {
  font-size: 12px;
  opacity: 0.9;
}

.status.online {
  color: #67C23A;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-actions .el-button {
  color: white;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f8f9fa;
}

.message {
  display: flex;
  margin-bottom: 16px;
  gap: 10px;
}

.message.user {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
}

.message.user .message-content {
  display: flex;
  justify-content: flex-end;
}

.message-bubble {
  background: white;
  border-radius: 18px;
  padding: 12px 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}

.message.user .message-bubble {
  background: #409EFF;
  color: white;
}

.message-text {
  line-height: 1.5;
  word-wrap: break-word;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  margin-top: 4px;
  text-align: right;
}

.message.user .message-time {
  text-align: left;
}

/* 打字动画 */
.typing-indicator {
  display: flex;
  gap: 4px;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  background: #409EFF;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.chat-input {
  padding: 20px;
  background: white;
  border-top: 1px solid #ebeef5;
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-replies {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.quick-reply-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.quick-reply-tag:hover {
  background: #409EFF;
  color: white;
}

.rating-content {
  text-align: center;
}
</style>
